<template>
    <main-wrap>
        <template v-slot:header>
            <Header title="新建收货地址"/>
        </template>
        <div class="formBox">
            <div class="formItem">
                <my-input class="adInput" v-model="form.linkName" type="text" label="收货人" placeholder="请输入收货人"/>
            </div>
            <div class="formItem">
                <my-input class="adInput" v-model="form.linkPhone" type="number" label="手机号" placeholder="请输入手机号"/>
            </div>
            <div class="formItem" @click="showArea = true">
                <my-input class="adInput" :readonly="true" v-model="areaSelectData" type="text" label="地区选择" placeholder="地区选择">
                    <template v-slot:right>
                        <i class="xzqu iconfont icon-xiangyoujiantou"></i>  
                    </template>
                </my-input>
            </div>
            <div class="formItem">
                <my-input class="adInput" v-model="form.street" type="text" label="详细地址" placeholder="请输入详细地址"/>
            </div>
        </div>
        <template v-slot:footer>
            <div class="adBtnBox">
                <my-button text="保存并使用" @click="onSubmit"/>
            </div>
        </template>
    </main-wrap>
    <van-popup v-model:show="showArea" position="bottom">
        <van-cascader
            class = "areaSelectCotaner"
            v-model="cascaderValue"
            title="请选择所在地区"
            :options="areaList"
            @close="showArea = false"
            @finish="onFinish"
            :field-names="fieldNames"
        />
    </van-popup>
</template>

<script>
import { reactive,toRefs,getCurrentInstance,onMounted,computed } from 'vue'
import {useRoute,useRouter} from 'vue-router'
import { useStore } from 'vuex'
import axios from 'axios'
import { 
    Cascader as vanCascader,
    Popup as vanPopup
} from 'vant';
import mainWrap from '@/components/mainWrap.vue'
import Header from '../../components/header.vue'
import myInput from '@/components/myInput.vue'
import myButton from '@/components/myButton.vue';
import {toast,checkMobile,mergeObject} from '@/utils/common.js'
export default {
    components:{
       mainWrap,
       Header,
       myInput,
       myButton,
       vanPopup,
       vanCascader
    },
    props:{

    },
    setup(props,context){
        const router = useRouter()
        const route = useRoute()
        const store = useStore()
        const {proxy} = getCurrentInstance()

        const state = reactive({
            useAdress:computed(()=>store.state.arApi.useAdress),
            backUrl:computed(()=>store.state.arApi.backUrl),
            form:{
                linkName:'',
                linkPhone:'',
                street:'',
                areaCode: "",
                areaName: "",
                cityCode: "",
                cityName: "",
                provinceCode: "",
                provinceName: ""
            },
            showArea:false,
            cascaderValue:'',
            areaList: [],
            fieldNames:{
                text: 'name',
                value: 'code',
                children: 'sub',
            },
            areaSelectData:'',
            selectOver:false, // 是否选择了省市区
            addressId:'',
            codeSuffix:'000000' // 编码后面加6个0
        })
        
        onMounted(()=>{
            state.addressId = route.query.id
            axios.get('/h5/json/area.json')
            .then(res=>{
                //console.log("json:",res.data)
                state.areaList = res.data
            })
            state.addressId && getAddressDetails()
        })

        const getAddressDetails = ()=>{
            store.dispatch('arApi/get_address_detail',state.addressId).then(res=>{
                state.form = mergeObject(state.form,res.data)
                state.areaSelectData = `${res.data.provinceName?res.data.provinceName+'/':''}${res.data.cityName?res.data.cityName+'/':''}${res.data.areaName?res.data.areaName:''}`
            })
        }

        // 全部选项选择完毕后，会触发 finish 事件
        const onFinish = ({ selectedOptions }) => {
            console.log("cascaderValue:",state.cascaderValue)
            state.showArea = false;
            state.selectOver = true
            state.areaSelectData = selectedOptions.map((option) => option.name).join('/');

            state.form.provinceCode = selectedOptions[0]?selectedOptions[0].code+state.codeSuffix:''
            state.form.provinceName = selectedOptions[0]?selectedOptions[0].name:''
            if(selectedOptions[0]){
               state.form.provinceCode =  selectedOptions[0].code+state.codeSuffix
               state.form.provinceName =  selectedOptions[0].name
            }
            if(selectedOptions[1]){
               state.form.cityCode =  selectedOptions[1].code+state.codeSuffix
               state.form.cityName =  selectedOptions[1].name
            }
            if(selectedOptions[2]){
               state.form.areaCode =  selectedOptions[2].code+state.codeSuffix
               state.form.areaName =  selectedOptions[2].name
            }
            console.log("state.form",state.form)
        };

        const onSubmit = async ()=>{
            console.log("selectOver:",state.selectOver)
            if(!state.form.linkName){
                return toast('请输入收货人姓名')
            }else if(!state.form.linkPhone){
                return toast('请输入收货人手机号')
            }else if(!checkMobile(state.form.linkPhone)){
               return toast('手机号输入有误')
            }else if(!state.addressId && !state.selectOver){
               return toast('请选择省市区')
            }else if(!state.form.street){
               return toast('请输入详细地址')
            }
            let res = ''
            const address=`${state.form.provinceName} ${state.form.cityName} ${state.form.areaName} ${state.form.street}`
            if(state.addressId){
                res = await store.dispatch('arApi/edit_address',{addresseeId:state.addressId,...state.form})
                if(res.success){
                    store.commit('arApi/set_useAdress',{
                        addresseeId:state.addressId,
                        address,
                        ...state.form
                    })
                    toast('修改成功')
                    if(state.backUrl){
                        router.push(state.backUrl)
                    }else{
                        router.back()
                    }
                }else{
                    toast('修改失败')
                }
            }else{
                res = await store.dispatch('arApi/add_address',state.form)
                if(res.success){
                    store.commit('arApi/set_useAdress',{
                        addresseeId:res.data.id,
                        address,
                        ...state.form
                    })
                    toast('添加成功')
                    if(state.backUrl){
                        router.push(state.backUrl)
                    }else{
                        router.back()
                    }
                }else{
                    toast('添加失败')
                }
            }
            
        }

        return{
            ...toRefs(state),
            onSubmit,
            onFinish
        }
    }
}
</script>

<style lang="scss" scoped>
    .formBox{
        padding: 30px 40px;
        .formItem{
            .xzqu{
                padding: 30px 0 0 0;
            }
        }
    }
    .adBtnBox{
        padding: 40px;
    }
</style>
<style lang="scss">
    .areaSelectCotaner{
        color: #333;
    }
</style>